# -*- encoding: utf-8 -*- 
from itertools import groupby
from datetime import datetime, timedelta
from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools import float_is_zero, float_compare, DEFAULT_SERVER_DATETIME_FORMAT
from odoo.tools.misc import formatLang
import odoo.addons.decimal_precision as dp

import os
import shutil

class fhcode_tb_wizard(models.Model):
    _name = 'fhcode.tb_wizard'
    _description = u'向导'
    _rec_name='f_nam'
    _order='create_date DESC'		
	
    def get_employee(self):
        obj = self.env['hr.employee']
        idsobj = obj.search([('user_id','=',self.env.user.id)])
        print('-------------------------------------')		
        print(self.env.user.id)		
        #print(ids)	
        res = idsobj.read()
        print(res)					
        return res and res[0]['id'] or 0
    f_nam= fields.Char(u'英文',readonly=False,required=False,translate=False)
    description= fields.Char(u'中文',readonly=False,required=False,translate=False)
    sql= fields.Char(u'sql',readonly=False,required=False,translate=False)
    ftype=fields.Selection([('0',u'sql'),('1',u'ir.actions.act_window'),('2',u'ir.actions.client'),('3',u'ir.actions.act_url')],u'类型',readonly=False,required=False,translate=False)
    furl= fields.Char(u'url',readonly=False,required=False,translate=False)
	
    fmodle= fields.Many2one('fhcode.tb_table', string=u'目标对象')  	
    modle_id = fields.Many2one('fhcode.tb_modle', string=u'模块')  	
    ftext= fields.Text(u'url',readonly=False,required=False,translate=False)
    FDisable=fields.Selection([('0',u'启用'),('1',u'停用')],u'是否停用',readonly=False,required=False,translate=False)
    order_line = fields.Many2many("fhcode.tb_base", 'fhcode_tbwizard_tbbase_rel', 'uid', 'gid', string=u'基本字段',)#fields.One2many('fhcode.tb_tableline', 'pay_id', string='Order Lines', copy=True)

	
	
    @api.multi
    def print_quotation(self):
	
	
        path=self.modle_id.fpath
        path2=self.modle_id.fpath2		
        t=os.path.exists(path)
        if(t==False):
            self.os_mkdir(path)	
	
	
	
	    #取模块的路径,没有则创建
        path=self.modle_id.fpath
        path2=self.modle_id.fpath2		
        t=os.path.exists(path+"\\wizard")
        if(t==False):
            self.os_mkdir(path+"\\wizard")
			
			
			
        oldname= path2+"\\Template\\wizard\\__init__.py"
        newname=path+"\\wizard\\__init__.py"
        t=os.path.exists(newname)		
        if(t==False):
			#self.os_mkdir(path)		
            shutil.copyfile(oldname,newname)		
        #shutil.copyfile(oldname,newname)				
        if(1==1):
            self.os_readlines(path2+"\\Template\\wizard\\Template_view.xml",path+"\\wizard\\"+self.modle_id.fname+"_"+self.f_nam+".xml")
            self.os_readlines_py(path2+"\\Template\\wizard\\Template.py",path+"\\wizard\\"+self.modle_id.fname+"_"+self.f_nam+".py")
			
		
		
        #self.os_readlines(path2+"\\Template\\Template_view.xml")
		
        return True

    def os_mkdir(self,path):

        os.mkdir(path)      
        return True

    def os_readlines(self,path,path2):

        # 打开文件
        fo = open(path, "r", encoding='UTF-8')
        print ("文件名为: ", fo.name)
        print ("文件名为2: ", self.description)
        print ("文件名为3: ", self.modle_id.fname+"."+self.f_nam)
		
		
        fields=self.os_fields()
        #print(fields)

        fieldsII=self.os_fieldsII()
        #print(fields)		
        lineST=""
        for line in fo.readlines():                          #依次读取每行  
            #line = line.strip()                             #去掉每行头尾空白
            line=line.replace("wizardFHsaasMK",self.modle_id.fname);		
            line=line.replace("FHsaasTB",self.f_nam);  			
            line=line.replace("FHsaasZW",self.description);            			
            line=line.replace("<fieldsfrom>",fieldsII);		
            #print(line)			
            lineST=lineST+line+""			
 
        # 关闭文件
        #print(lineST)


        fo = open(path2, "w", encoding='UTF-8')
        #print "文件名为: ", fo.name
        #str = "菜鸟教程"
        fo.write(lineST)
        fo.close()      
        return True
		
    def os_fields(self):
        ls=""
		
        res = sorted(self.order_line, key=lambda l: l[0].id)		
        for line in res:
            if(ls==""):			
                ls=ls+'<field name="'+line.fen+'" />\n'			
            else:			
                ls=ls+'                  '+'<field name="'+line.fen+'" />\n'			
        #os.mkdir(path)      
        return ls		
		
		
    def os_fieldsII(self):
        ls=""
        res = sorted(self.order_line, key=lambda l: l[0].id)		
        for line in res:
            if(line.ftype!="many2many"):		
                if(ls==""):
                    if(line.required==True):			
                        ls=ls+'<field name="'+line.fen+'"  required="1" />\n'	
                    else:			
                        ls=ls+'<field name="'+line.fen+'" />\n'						
                else:
                    if(line.required==True):
                        ls=ls+'						'+'<field name="'+line.fen+'" required="1" />\n'
                    else:
                        ls=ls+'						'+'<field name="'+line.fen+'" />\n'	


            if(line.ftype=="many2many"):		
                if(ls==""):
                    if(line.required==True):			
                        ls=ls+'<field name="'+line.fen+'"  widget="many2many_tags" required="1" />\n'	
                    else:			
                        ls=ls+'<field name="'+line.fen+'" widget="many2many_tags"  />\n'						
                else:
                    if(line.required==True):
                        ls=ls+'						'+'<field name="'+line.fen+'" required="1" widget="many2many_tags"   />\n'
                    else:
                        ls=ls+'						'+'<field name="'+line.fen+'"  widget="many2many_tags" />\n'				
        #os.mkdir(path)      
        return ls
		
		
		
    def os_readlines_py(self,path,path2):

        # 打开文件
        fo = open(path, "r", encoding='UTF-8')
        print ("文件名为: ", fo.name)
        print ("文件名为2: ", self.description)
        print ("文件名为3: ", self.modle_id.fname+"."+self.f_nam)
        fieldsII=self.os_fieldsII_py()
        print(fieldsII)		
        lineST=""
        for line in fo.readlines():                          #依次读取每行  
            #line = line.strip()                             #去掉每行头尾空白
            line=line.replace("FHsaasMK",self.modle_id.fname);		
            line=line.replace("FHsaasTB",self.f_nam);  			
            line=line.replace("FHsaasZW",self.description);            			
            line=line.replace("FHSAAS_columns",fieldsII);
            '''line=line.replace("<fields>",fields.encode(encoding='UTF-8'));'''			
            print(line)			
            lineST=lineST+line+""			

        # 关闭文件
        #print(lineST)


        fo = open(path2, "w", encoding='UTF-8')
        fo.write(lineST)
        fo.close()      
        return True		
    def os_fieldsII_py(self):
        ls=""
		
        res = sorted(self.order_line, key=lambda l: l[0].id)			
        for line in res:
            if(line.ftype=="char"):		
                ls=ls+"    "+line.fen+"=fields.Char(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"

            if(line.ftype=="integer"):		
                ls=ls+"    "+line.fen+"=fields.Integer(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	

            if(line.ftype=="float"):		
                ls=ls+"    "+line.fen+"=fields.Float(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	

            if(line.ftype=="boolean"):		
                ls=ls+"    "+line.fen+"=fields.Boolean(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	
				
            if(line.ftype=="selection"):		
                ls=ls+"    "+line.fen+"=fields.Selection([('0',u'KEY1'),('1',u'KEY2')],u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	
				
            if(line.ftype=="date"):		
                ls=ls+"    "+line.fen+"=fields.Date(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	


            if(line.ftype=="datetime"):		
                ls=ls+"    "+line.fen+"=fields.Datetime(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	

            if(line.ftype=="text"):		
                ls=ls+"    "+line.fen+"=fields.Text(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"	

            if(line.ftype=="function"):		
                ls=ls+"    "+line.fen+"=fields.Text(u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"

            if(line.ftype=="many2one"):		
                ls=ls+"    "+line.fen+"=fields.Many2one('"+line.many2oneII+"',u'"+line.fname+"',readonly=False,required=False,translate=False)"+"\n"

            if(line.ftype=="many2many"):		
                ls=ls+"    "+line.fen+"=fields.Many2many('"+line.many2manyII+"','many2man_"+self.modle_id.fname+"_"+self.f_nam+"_"+line.fen+"_rel', 'uid', 'gid', u'"+line.fname+"',)"+"\n"
				
	
				
        return ls	
	
	
	
		
    @api.model		
    def action_funproved0(self):
        #context = context or {}
        t=fields.datetime.now()
        #huid=self.get_employee(cr,uid,context)
        self.write({'state':'wait_prove','FAdddate':t})       
        return True
		
    @api.model		
    def action_funproved(self):
        #context = context or {}
        t=fields.datetime.now()
        #huid=self.get_employee(cr,uid,context)
        self.write({'state':'proved','FAdddate':t})       
        return True		
    @api.model		
    def create(self, vals):
        result = super(fhcode_tb_wizard, self).create(vals)	
        return result
    @api.multi		
    def write(self, values):
	    
        result = super(fhcode_tb_wizard, self).write(values)		
		
        return result
    @api.multi
    def unlink(self):
	
        return super(fhcode_tb_wizard, self).unlink()
    @api.multi
    def copy(self, default=None):
        return super(fhcode_tb_wizard, self).copy(default)
    @api.multi
    def search(self, args, offset=0, limit=None, order=None, context=None, count=False):
        domain =None		
        domain = [('state', '=', '0')]		
        return super(fhcode_tb_wizard, self).search(args, offset=offset, limit=limit, order=order, count=count)
		
fhcode_tb_wizard() #对象定义结束
